import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }


    class Solution {
        //线性表非递归前序遍历
        public List<Integer> preorderTraversal(TreeNode root) {
            // 存储遍历结果
            List<Integer> result = new ArrayList<>();
            // 用ArrayList模拟栈，存储TreeNode类型
            List<TreeNode> stack = new ArrayList<>();

            if (root == null) {
                return result;
            }

            TreeNode cur = root;

            while (cur != null || !stack.isEmpty()) {
                // 遍历左子树，先访问节点再入栈
                while (cur != null) {
                    result.add(cur.val); // 将节点值加入结果列表
                    stack.add(cur);      // 节点入栈
                    cur = cur.left;      // 移动到左子节点
                }

                // 左子树遍历完毕，出栈
                cur = stack.remove(stack.size() - 1);
                // 转向右子树
                cur = cur.right;
            }

            return result;
        }

        //线性表非递归中序遍历
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> list = new ArrayList<>();
            Stack<TreeNode> stack = new Stack<>();
            if (root == null) {
                return list;

            }
            TreeNode cur = root;
            while (cur != null || !stack.isEmpty()) {
                while (cur != null) {

                    stack.push(cur);
                    cur = cur.left;
                }
                TreeNode top = stack.pop();
                list.add(top.val);
                cur = top.right;
            }
            return list;
        }

    }
    public List<Integer> postorderTraversal(TreeNode root){
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while (cur!=null||!stack.isEmpty()){
            while (cur!=null){
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if(top.right==null||prev == top.right){
                list.add(top.val);
                prev = top;
                stack.pop();
            }else {
                cur = top.right;
            }

        }
        return list;
    }

}